package org.kernely.ui.mvp;
import java.util.ArrayList;

/**
 * Every user session has it own instance of KernelyEventBus, that broadcast events
 * to the UI components that want so (essentially presenters, instances of Presenter class).
 * See the wiki for more documentation.
 */
public class KernelyEventBus{
	
	private ArrayList<KernelyEventReceiver> eventsListeners = new ArrayList<KernelyEventReceiver>();

	public KernelyEventBus(){
		KernelyEventBusGeneral.getInstance().addEventBus(this);
	}
	
	/**
	 *  Add a listener to the event bus.
	 *  @param listener The listener to add.
	 */
	public final synchronized void addListener(KernelyEventReceiver listener) {
		eventsListeners.add(listener);
	}
	
	/**
	 *  Remove a listener from the event bus.
	 *  @param listener The listener to remove.
	 */
	public final synchronized void removeListener(KernelyEventReceiver listener) {
		eventsListeners.remove(listener);
	}
	
	/**
	 * Broadcast an event to all the registered event listeners in the user session.
	 * @param event The event to broadcast.
	 */
	@SuppressWarnings("unchecked")
	public final synchronized void broadcastEvent(KernelyEvent event){
		if (event != null){
			ArrayList<KernelyEventReceiver> list = (ArrayList<KernelyEventReceiver>) eventsListeners.clone();
			for(KernelyEventReceiver listener : list){
				listener.handleKernelyEvent(event);
			}
		}
	}
}